import "./reset.css";
import dayjs from "dayjs";
import roleForm from "../form/role.vue";
import editForm from "../form/index.vue";
import { zxcvbn } from "@zxcvbn-ts/core";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import userAvatar from "@/assets/user.jpg";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import ReCropperPreview from "@/components/ReCropperPreview";
import type { FormItemProps, RoleFormItemProps } from "../utils/types";
import { GridifyQueryBuilder, ConditionalOperator as op } from "gridify-client";
import {
  getKeyList,
  isAllEmpty,
  hideTextAtIndex,
  deviceDetection
} from "@pureadmin/utils";
import { getAllOrganizations } from "@/swagger/api/organization";
import {
  createUser as create,
  updateUser as update,
  queryUsers,
  setUserEnabledStatus,
  batchDeleteUser as batchDelete,
  getUserRoleById,
  assignRoleToUser,
  resetPassword,
  uploadAvatar
} from "@/swagger/api/user";
import {
  getAllRoles as getAllRolesQuery
} from "@/swagger/api/role";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElProgress,
  ElMessageBox
} from "element-plus";
import {
  type Ref,
  h,
  ref,
  toRaw,
  watch,
  computed,
  reactive,
  onMounted
} from "vue";
import { hasPerms } from "@/utils/auth";
import { usePermissionFooterButtons } from "@/utils/usePermissionFooterButtons";
import { useUserStoreHook } from "@/store/modules/user";
const { VITE_GLOBAL_API_URL } = import.meta.env;

export function useUser(tableRef: Ref, treeRef: Ref) {
  const form = reactive({
    // 左侧组织树的id
    organizationId: "",
    username: "",
    phoneNumber: "",
    enabled: ""
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  // 上传头像信息
  const avatarInfo = ref();
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const higherDeptOptions = ref();
  const treeData = ref([]);
  const treeLoading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "用户编号",
      prop: "id",
      width: 90,
      formatter: ({ id }) => {
        const str = String(id || '');
        return str.length <= 13 ? str : str.slice(-12);
      }
    },
    {
      label: "用户头像",
      prop: "avatar?.url",
      cellRenderer: ({ row }) => {
        const baseUrl = import.meta.env.VITE_GLOBAL_API_URL;
        const avatarUrl = row.avatar?.url;

        // 判断是否为完整 URL（以 http 开头）
        const fullUrl = avatarUrl
          ? (avatarUrl.startsWith("http") ? avatarUrl : baseUrl + avatarUrl)
          : userAvatar;
        const userStore = useUserStoreHook();
        if (userStore.username === row.username) {
          userStore.SET_AVATAR(row.avatar)
        }
        return (
          <el-image
            fit="cover"
            preview-teleported={true}
            src={fullUrl}
            preview-src-list={[fullUrl]}
            class="w-[24px] h-[24px] rounded-full align-middle"
          />
        );
      },
      width: 90
    },
    {
      label: "用户名称",
      prop: "username",
      minWidth: 130
    },
    {
      label: "用户昵称",
      prop: "nickname",
      minWidth: 130
    },
    {
      label: "性别",
      prop: "gender",
      minWidth: 90,
      cellRenderer: ({ row, props }) => {
        // 定义性别映射表
        const genderMap = {
          0: { text: "男", type: "success" },
          1: { text: "女", type: "danger" },
          2: { text: "保密", type: "info" }
        };

        // 根据 gender 获取对应显示项
        const gender = genderMap[row.gender] ?? genderMap[0];

        return (
          <el-tag size={props.size} type={gender.type} effect="plain">
            {gender.text}
          </el-tag>
        );
      }
    },
    {
      label: "手机号码",
      prop: "phoneNumber.value",
      minWidth: 90,
      formatter: (row) =>
        row.phoneNumber?.value
          ? hideTextAtIndex(row.phoneNumber.value, { start: 3, end: 6 })
          : ''
    },
    {
      label: "组织机构",
      prop: "organizationName",
      minWidth: 90
    },
    {
      label: "状态",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.enabled}
          active-value={true}
          inactive-value={false}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      ),
      minWidth: 90
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "created",
      formatter: ({ created }) =>
        dayjs(created).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });
  const pwdProgress = [
    { color: "#e74242", text: "非常弱" },
    { color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  // 当前密码强度（0-4）
  const curScore = ref();
  const roleOptions = ref([]);

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${row.enabled === false ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${row.username
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(async () => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          await setUserEnabledStatus({ id: row.id }, { id: row.id, enabled: row.enabled });
          message(`已${row.enabled === false ? "停用" : "启用"}${row.username}`, {
            type: "success"
          });
        }, 1);
      })
      .catch(() => {
        row.enabled === false ? (row.enabled = true) : (row.enabled = false);
      });
  }

  function handleUpdate(row) {
    console.log(row);
  }

  async function handleDelete(row) {
    await batchDelete({ userIds: [row.id] })
    message(`您删除了用户编号为${row.id}的这条数据`, { type: "success" });
    onSearch();
  }

  function handleSizeChange(val: number) {
    onSearch();
  }

  function handleCurrentChange(val: number) {
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const query = new GridifyQueryBuilder()
      .setPage(pagination.currentPage)
      .setPageSize(pagination.pageSize)
      .addOrderBy("created", true)
      .addCondition("username", op.Contains, form.username);

    if (form.phoneNumber) {
      query.and().addCondition("phoneNumber", op.Contains, form.phoneNumber);
    }
    if (form.enabled !== "" && form.enabled !== undefined) {
      query.and().addCondition("enabled", op.Equal, form.enabled);
    }
    if (form.organizationId !== "" && form.organizationId !== undefined) {
      query.and().addCondition("organizationId", op.Equal, form.organizationId);
    }

    const queryBuilder = query.build() as any;
    const { data } = await queryUsers(queryBuilder) as any;

    dataList.value = data.items;
    pagination.total = data.totalItems;
    pagination.currentPage = data.currentPage;

    loading.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.organizationId = "";
    treeRef.value.onTreeReset();
    onSearch();
  };

  function onTreeSelect({ id, selected }) {
    form.organizationId = selected ? id : "";
    onSearch();
  }

  function formatHigherDeptOptions(treeList) {
    // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级组织级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = treeList[i].enabled === false ? true : false;
      formatHigherDeptOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    console.log(row);
    addDialog({
      title: `${title}用户`,
      props: {
        formInline: {
          userId: row?.id ?? "",
          title,
          higherDeptOptions: formatHigherDeptOptions(higherDeptOptions.value),
          parentId: row?.id ?? null,
          nickname: row?.nickname ?? "",
          username: row?.username ?? "",
          password: row?.password ?? "",
          /*@ts-ignore*/
          phoneNumber: row?.phoneNumber?.value ?? "",
          email: row?.email ?? "",
          gender: row?.gender ?? 0,
          organizationId: row?.organizationId ?? null,
          description: row?.description ?? "",
          enabled: row?.enabled ?? true,
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了用户名称为${curData.username}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              /* @ts-ignore */
              await create(curData)
              chores();
            } else {
              /* @ts-ignore */
              await update({ id: curData.id }, curData)
              chores();
            }
          }
        });
      }
    });
  }

  const cropRef = ref();
  /** 上传头像 */
  function handleUpload(row) {
    const baseUrl = import.meta.env.VITE_GLOBAL_API_URL;
    const avatarUrl = row.avatar?.url;

    // 判断是否为完整 URL（以 http 开头）
    const fullUrl = avatarUrl
      ? (avatarUrl.startsWith("http") ? avatarUrl : baseUrl + avatarUrl)
      : userAvatar;
    addDialog({
      title: "裁剪、上传头像",
      width: "40%",
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () =>
        h(ReCropperPreview, {
          ref: cropRef,
          imgSrc: fullUrl || userAvatar,
          onCropper: info => (avatarInfo.value = info)
        }),
      beforeSure: async done => {
        await uploadAvatar({ id: row.id }, { userId: row.id, avatarBase64: avatarInfo.value.base64 })
        done(); // 关闭弹框
        onSearch(); // 刷新表格数据
      },
      closeCallBack: () => cropRef.value.hidePopover()
    });
  }

  watch(
    pwdForm,
    ({ newPwd }) =>
      (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  );

  /** 重置密码 */
  function handleReset(row) {
    addDialog({
      title: `重置 ${row.username} 用户的密码`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      footerButtons: usePermissionFooterButtons(["User:Reset:Password"]),
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <>
          <ElForm ref={ruleFormRef} model={pwdForm}>
            <ElFormItem
              prop="newPwd"
              rules={[
                {
                  required: true,
                  message: "请输入新密码",
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={pwdForm.newPwd}
                placeholder="请输入新密码"
              />
            </ElFormItem>
          </ElForm>
          <div class="my-4 flex">
            {pwdProgress.map(({ color, text }, idx) => (
              <div
                class="w-[19vw]"
                style={{ marginLeft: idx !== 0 ? "4px" : 0 }}
              >
                <ElProgress
                  striped
                  striped-flow
                  duration={curScore.value === idx ? 6 : 0}
                  percentage={curScore.value >= idx ? 100 : 0}
                  color={color}
                  stroke-width={10}
                  show-text={false}
                />
                <p
                  class="text-center"
                  style={{ color: curScore.value === idx ? color : "" }}
                >
                  {text}
                </p>
              </div>
            ))}
          </div>
        </>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: done => {
        ruleFormRef.value.validate(async valid => {
          if (valid) {
            await resetPassword({ id: row.id }, { userId: row.id, newPassword: pwdForm.newPwd });
            message(`已成功重置 ${row.username} 用户的密码`, {
              type: "success"
            });
            done(); // 关闭弹框
            onSearch(); // 刷新表格数据
          }
        });
      }
    });
  }

  /** 分配角色 */
  async function handleRole(row) {
    // 选中的角色列表
    const ids = (await getUserRoleById({ id: row.id })).data ?? [];
    addDialog({
      title: `分配 ${row.username} 用户的角色`,
      props: {
        formInline: {
          username: row?.username ?? "",
          nickname: row?.nickname ?? "",
          roleOptions: roleOptions.value ?? [],
          ids
        }
      },
      width: "400px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      footerButtons: usePermissionFooterButtons(["User:Role:Assign"]),
      contentRenderer: () => h(roleForm),
      beforeSure: async (done, { options }) => {
        const curData = options.props.formInline as RoleFormItemProps;
        /* @ts-ignore */
        await assignRoleToUser({ id: row.id }, { userId: row.id, roleIds: curData.ids });
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
      }
    });
  }

  onMounted(async () => {
    treeLoading.value = true;
    onSearch();

    if (hasPerms(["Organization:View:All"])) {
      // 归属组织
      const { data } = (await getAllOrganizations()) as any;
      higherDeptOptions.value = handleTree(data);
      treeData.value = handleTree(data);
      treeLoading.value = false;
    }
    if (hasPerms(["Role:View:All"])) {
      // 角色列表
      /* @ts-ignore */
      roleOptions.value = (await getAllRolesQuery()).data;
    }
  });

  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    onTreeSelect,
    handleUpdate,
    handleDelete,
    handleUpload,
    handleReset,
    handleRole,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
